<template>
  <div class="crud">
    <!--Filter-->
    <FilterData
      :config="filterConfig"
      :filter-data="listQuery"
      @filter="filterSearch"
    />
    <!--Filter end-->

    <!--crud主体内容区，展示表格内容-->
    <component
      :is="gridListComponent"
      ref="curdTable"
      :list-loading="listLoading"
      :show-grid-data="showGridData"
      :grid-config="gridConfig"
      :grid-handles="buttonActionHandles"
      :hide-edit-area="hideEditArea"
      :grid-edit-width="gridEditWidth"
      :lazy="lazy"
      :multiple="multiple"
      :tree-props="treeProps"
      size="mini"
      style="width: 100%"
      @action="onAction"
      @select="onSelect"
    >
      <div
        slot="append"
        class="crud-footer__content"
      >
        <slot name="handle" />
        <!--分页-->
        <pagination
          v-show="meta.totalCount>0"
          v-if="!hidePagination"
          :total="meta.totalCount"
          :limit="meta.perPage"
          :page.sync="listQuery.page"
          @currentPage="meta.currentPage"
          @pageSize="meta.perPage"
          @pagination="getData"
        />
      </div>
    </component>
    <!--crud按钮触发的表单弹窗-->
    <BaseDialogForm
      ref="dialogForm"
      :title="dialogTitle"
      :config="formConfig"
      :width="dialogWidth"
      :form-data="formModel"
      @submit="dialogSubmit"
    />
  </div>
</template>

<script>
import FilterData from './components/filter'
import GridAdvenceView from './components/GridAdvenceView'
import GridTableView from './components/GridTableView'
import GridTreeView from './components/GridTreeView'
import Pagination from '@/components/Pagination'
import BaseDialogForm from './components/BaseDialogForm'

export default {
  name: 'GridListview',
  components: {
    FilterData,
    GridTreeView,
    GridAdvenceView,
    GridTableView,
    Pagination,
    BaseDialogForm
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  provide() {
    return {
      apiRequestMethod: this.apiRequestMethod
    }
  },
  props: {
    // 表单标题，例如用户、角色
    formTitle: {
      type: String,
      default: ''
    },
    // 表单配置
    formConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表单的model数据
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    // 表格配置
    gridConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表格配置
    filterConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表格按钮配置
    gridBtnConfig: {
      type: Object,
      default() {
        return null
      }
    },
    // 表格按钮配置
    gridHandles: {
      type: Array,
      default() {
        return []
      }
    },
    treeProps: {
      type: Object,
      default: null
    },
    // 判断是否是异步数据
    lazy: {
      type: Boolean,
      default: false
    },
    // 是否多选表格
    multiple: {
      type: Boolean,
      default: false
    },
    // 表格死数据
    gridType: {
      type: String,
      default: ''
    },
    // 表格死数据
    gridData: {
      type: Array,
      default() {
        return []
      }
    },
    // 数据接口
    apiService: {
      type: [Object, Function],
      default: null
    },
    // 判断是否是异步数据
    isAsync: {
      type: Boolean,
      default: true
    },
    //  表格编辑区域宽度
    gridEditWidth: {
      type: Number,
      default: 0
    },
    //  是否隐藏表格操作
    hideEditArea: {
      type: Boolean,
      default: false
    },
    //  是否隐藏表格操作
    hidePagination: {
      type: Boolean,
      default: false
    },
    // 判断是否是异步数据
    bindParams: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 新增修改模态框title
      dialogTitle: '',
      dialogWidth: '',
      // 展示的表格数据，数据来源可能是父组件传递的固定数据，可能是接口请求数据
      showGridData: [],
      meta: {
        // 列表数据总数
        totalCount: 0,
        pageCount: 1,
        // 当前页码
        currentPage: 1,
        // 每页显示数量
        perPage: 20
      },
      listQuery: {
        page: 1
      },
      // 表单数据
      formModel: {},
      //  表格加载状态
      listLoading: false
    }
  },
  computed: {
    gridListComponent() {
      if (this.gridType === 'tree') {
        return 'GridTreeView'
      } else if (this.gridType === 'advence') {
        return 'GridAdvenceView'
      } else {
        return this.treeProps ? 'GridTreeView' : 'GridTableView'
      }
    },
    gridButtons() {
      var buttons = []
      if (this.gridBtnConfig) {
        if (this.gridBtnConfig.view) {
          buttons.push({
            name: '查看',
            emitName: 'view'
          })
        } else if (this.gridBtnConfig.update) {
          buttons.push({
            name: '修改',
            emitName: 'update'
          })
        } else if (this.gridBtnConfig.delete) {
          buttons.push({
            name: '删除',
            emitName: 'delete'
          })
        } else {
          if (this.gridBtnConfig.expands && this.gridBtnConfig.expands.length > 0) {
            this.gridBtnConfig.expands.map(item => {
              buttons.push({
                name: item.name,
                emitName: item.emitName
              })
            })
          }
        }
      }
      return buttons
    },
    buttonActionHandles() {
      return [...this.gridHandles, ...this.gridButtons]
    }
  },
  watch: {
    // 防止表格预置数据不成功，涉及生命周期问题
    gridData() {
      this.showGridData = this.gridData
    },
    // 防止表格预置数据不成功，涉及生命周期问题
    bindParams() {
      this.refresh()
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 获取列表数据
    getData(params = null) {
      this.listLoading = true
      const queryParams = Object.assign(this.listQuery, this.bindParams, params)
      this.apiRequestMethod(queryParams).then(
        response => {
          const { data } = response
          this.showGridData = data.items
          this.meta = data.meta
          this.listLoading = false
        },
        error => {
          console.log(error)
          this.listLoading = false
        }
      )
    },
    apiRequestMethod(queryParams) {
      if (typeof this.apiService === 'function') {
        return this.apiService(queryParams)
      } else {
        return this.apiService.list(queryParams)
      }
    },
    createOrUpdate(item) {
      this.$refs.dialogForm.resetForm()
      // 新增时，模态框数据需要拷贝基础定义的数据模型，修改时，直接拷贝当前行数据
      this.formModel = item ? Object.assign({}, item) : Object.assign({}, this.formData)
      this.dialogTitle = (item ? '修改' : '新增') + this.formTitle
      this.$refs.dialogForm.showDialog()
    },
    onAction(name, data) {
      this.$emit('action', name, data)
    },
    onSelect(value) {
      this.$emit('select', value)
    },
    handleCurrentChange(page) {
      this.meta.currentPage = page
      this.getData()
    },
    handleSizeChange(size) {
      this.meta.perPage = size
      this.getData()
    },
    // 刷新数据
    refresh() {
      this.getData()
    },
    // Filter数据检索提交
    filterSearch(data) {
      this.listQuery.page = 1
      this.getData(data)
    },
    // 模态框数据提交
    dialogSubmit(data) {
      this.apiService[data.userId ? 'update' : 'create'](data).then(res => {
        this.getData()
        this.$message.success(this.dialogTitle + '成功！')
      })
    },
    onRemove(data) {
      //  处理删除逻辑
      this.apiService.delete(data.id).then(res => {
        this.getData()
        this.$message.success('删除成功！')
      })
    },
    view(data) {
      // 处理查看详情逻辑
      this.$router.push({
        path: 'view/' + data.id
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// @import 'components/grid.scss';
</style>
